<?php

namespace Wap\Controller;

use Wap\Service\WeixinService;
use User\Model\QuestionnaireModel;

class QuestionnaireController extends WapController
{
    public $wxuser;//活动绑定的微信号--
    public $_questionnaire;//问卷测试--

    public function __construct()
    {
        parent::__construct();

        $this->handleCriteriaWxuser();
    }

    //微信公众号信息
    private function handleCriteriaWxuser()
    {
        $id = I("get.id", -1, "");
        if ($_SERVER['HTTP_HOST'] == '192.168.1.137') {
            session('questionnaire_openid_' . $id, 111);
            session('questionnaire_headimgurl_' . $id, "");
            session('questionnaire_nickname_' . $id, "");
        }

        if ($id && $id != -1) {
            $this->_questionnaire = M("questionnaire")->where(['id' => $id])->field("token,need_register,reserve")->find();
            $this->wxuser = WeixinService::getWxuser($this->_questionnaire['token']);
        }
    }

    public function index()
    {
        $id = I("get.id", -1, "");
        //pv、uv
        $this->_statistics($id);
        $openid = session('questionnaire_openid_' . $id);
        $headurl = session('questionnaire_headimgurl_' . $id);
        $nickname = session('questionnaire_nickname_' . $id);
        //微信分享
        $wx = WeixinService::getWxuser($this->wxuser['token']);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $wx_config = array(
                'appId' => $wx['appid'],
                'nonceStr' => $wxJSApi['noncestr'],
                'timestamp' => $wxJSApi['timestamp'],
                'signature' => $wxJSApi['sha1']
            );
        }
        $where_questionnaire["id"] = $id;
        $questionnaire = M("questionnaire")->where($where_questionnaire)
            ->field("title,share_title,share_desc,share_link,share_image")->find();
        $share_data = array(
            'share_title' => $questionnaire['share_title'] ? $questionnaire['share_title'] :
                $questionnaire['title'],
            'share_desc' => $questionnaire['share_desc'] ? $questionnaire['share_desc'] :
                "邀请你的好友一起来测一测！",
            'share_link' => $questionnaire['share_link'] ? $questionnaire['share_link'] :
                C('SITE_URL') . '/Wap/Questionnaire/index?id=' . $id,
            'share_image' => $questionnaire['share_image'] ? C('SITE_URL') . $questionnaire['share_image'] :
                '/Public/images/questionnaire/share_image.jpg',
        );
        if($this->_is_weixin()){
            if ($this->_questionnaire['need_register']) {
                if (!empty($nickname) && !empty($headurl) && !empty($openid)) {
                    $this->assign("wx_config", $wx_config);
                    $this->assign("share_data", $share_data);
                    return $this->display('index');
                }
            } else {
                if (!empty($openid)) {
                    $this->assign("wx_config", $wx_config);
                    $this->assign("share_data", $share_data);
                    return $this->display('index');
                }
            }
            $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
            if ($this->_questionnaire['need_register']) {
                $url = $wechat->snsapiUserInfoLink("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Questionnaire/entry?id=" .
                    $id, $this->wxuser['appid']);
            } else {
                $url = $wechat->buildOauthURI("http://" . $_SERVER['HTTP_HOST'] . "/Wap/Questionnaire/entry?id=" . $id);
            }
            redirect($url);
        }else{
            if(!$openid){
                if(cookie("token")){
                    $openid = cookie("token");
                }else{
                    $openid = $this->_getRandCode();
                    cookie("token", $openid, 60 * 60 * 24 * 30);//一个月
                }
                session('questionnaire_openid_' . $id, $openid);
                session('questionnaire_headimgurl_' . $id, "");
                session('questionnaire_nickname_' . $id, "游客_".$openid);
            }
            $this->assign("wx_config", $wx_config);
            $this->assign("share_data", $share_data);
            $this->display('index');
        }
    }

    public function entry()
    {
        $code = I("get.code", "", "");
        $id = I("get.id", "", "");
        $openid = '';
        $wechat = new \Wap\Service\WechatService($this->wxuser['appid'], $this->wxuser['appsecret']);
        if ($this->_questionnaire['need_register']) {
            $out = $wechat->snsapiUserInfo($this->wxuser['appid'], $this->wxuser['appsecret'], $code);
            if ($out != null) {
                $openid = $out['openid'];
                session('questionnaire_nickname_' . $id, $out['nickname']);
                session('questionnaire_headimgurl_' . $id, $out['headimgurl']);
            }
        } else {
            $openid = $wechat->snsapiBaseUser($code);
        }
        session('questionnaire_openid_' . $id, $openid);
        //微信分享
        $wx = WeixinService::getWxuser($this->wxuser['token']);
        $wxJSApi = WeixinService::buildWXJSApi($wx);
        if (!empty($wxJSApi)) {
            $wx_config = array(
                'appId' => $wx['appid'],
                'nonceStr' => $wxJSApi['noncestr'],
                'timestamp' => $wxJSApi['timestamp'],
                'signature' => $wxJSApi['sha1']
            );
        }
        $where_questionnaire["id"] = $id;
        $questionnaire = M("questionnaire")->where($where_questionnaire)
            ->field("title,share_title,share_desc,share_link,share_image")->find();
        $share_data = array(
            'share_title' => $questionnaire['share_title'] ? $questionnaire['share_title'] :
                $questionnaire['title'],
            'share_desc' => $questionnaire['share_desc'] ? $questionnaire['share_desc'] :
                "邀请你的好友一起来测一测！",
            'share_link' => $questionnaire['share_link'] ? $questionnaire['share_link'] :
                C('SITE_URL') . '/Wap/Questionnaire/index?id=' . $id,
            'share_image' => $questionnaire['share_image'] ? C('SITE_URL') . $questionnaire['share_image'] :
                '/Public/images/questionnaire/share_image.jpg',
        );
        $this->assign("wx_config", $wx_config);
        $this->assign("share_data", $share_data);
        $this->display('index');
    }

    private function _is_weixin() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }

    private function _getRandCode()
    {
        $charts = "abcdefghjkmnpqrstuvwxyz0123456789";
        $max = strlen($charts);
        $noncestr = "";
        for($i = 0; $i < 7; $i++)
        {
            $noncestr .= $charts[mt_rand(0, $max)];
        }
        return $noncestr;
    }

    //------------------------------------------------接口部分--------------------------------------------------

    public function getActivityStatus()
    {
        $id = I("get.id", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        $time = date('Y-m-d H:i:s');
        $questionnaire = M("questionnaire")->where(["id" => $id])->field("startdate,enddate,status,reserve")->find();
        if ($questionnaire['reserve'] > 0) {
            $cond['status'] = QuestionnaireModel::ANSWER_ACTIVE;
            $cond['questionnaire_id'] = $id;
            $cond['openid'] = session('questionnaire_openid_' . $id);
            $valid_start = date("Y-m-d") . " 00:00:00";
            $valid_end = date("Y-m-d") . " 23:59:59";
            $cond['startdate'] = array("between", array($valid_start, $valid_end));
            $count = M("questionnaire_fans")->where($cond)->count();
            if ($count >= $questionnaire['reserve']) {
                $this->ajaxReturn(array('status' => -1, 'msg' => '次数已用完'));
            }
        }
        if ($questionnaire['status'] == QuestionnaireModel::QUESTIONNAIRE_ACTIVE) {
            if ($questionnaire['startdate'] > $time) {
                $this->ajaxReturn(array('status' => -1, 'msg' => '活动还未开始'));
            } elseif ($questionnaire['enddate'] < $time) {
                $this->ajaxReturn(array('status' => -1, 'msg' => '活动已结束'));
            } else {
                $this->ajaxReturn(array('status' => 1, 'msg' => '活动正常'));
            }
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => '活动已关闭'));
        }
    }

    public function getActivityInfo()
    {
        $id = I("get.id", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        $questionnaire = M("questionnaire")->where(["id" => $id, "status" => QuestionnaireModel::QUESTIONNAIRE_ACTIVE])
            ->field("title,title_image,rules,background_image,button_image,theme_color,background_music,need_music")->find();
        $questionnaire['title_image'] = $questionnaire['title_image'] ? C('SITE_URL') . $questionnaire['title_image'] : C('SITE_URL') . '/Public/images/questionnaire/title_image.jpg';
        $questionnaire['background_image'] = $questionnaire['background_image'] ? C('SITE_URL') . $questionnaire['background_image'] : C('SITE_URL') . '/Public/images/questionnaire/background.jpg';
        $questionnaire['button_image'] = $questionnaire['button_image'] ? C('SITE_URL') . $questionnaire['button_image'] : '';
        if ($questionnaire["need_music"] == QuestionnaireModel::MUSIC_ON) {
            if ($questionnaire['background_music']) {
                $questionnaire['background_music'] = C("SITE_URL") . $questionnaire['background_music'];
            } else {
                $questionnaire['background_music'] = C("SITE_URL") . "/Public/audio/questionnaire/background_music.mp3";
            }
        } else {
            $questionnaire['background_music'] = "";
        }
        if (!empty($questionnaire)) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '获取问卷测试信息成功', 'questionnaire' => $questionnaire));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => '获取问卷测试信息失败'));
        }
    }

    public function getQuestions()
    {
        $id = I("get.id", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }

        //--获取测试问卷活动信息--
        $where_questionnaire["id"] = $id;
        $where_questionnaire["status"] = QuestionnaireModel::QUESTIONNAIRE_ACTIVE;
        $questionnaire = M("questionnaire")->where($where_questionnaire)->find();
        if (!empty($questionnaire)) {
            $where_questions["questionnaire_id"] = $id;
            $where_questions["type"] = QuestionnaireModel::TYPE_MAIN;
            $where_questions["status"] = QuestionnaireModel::QUESTION_ACTIVE;
            $questions = array();
            if ($questionnaire['has_random'] == QuestionnaireModel::RANDOM_ON) {
                $return = $this->getRandomQuestion($id);
                $where_questions["displayorder"] = array("IN", $return);
            }
            //--获取所有题目$questions--
            $questions = M("questionnaire_questions")->where($where_questions)->field("id as question_id,title,is_single")
                ->order("displayorder asc")->select();
            if (!empty($questions)) {
                $ids = array();
                //--将题目id放到ids[]中--
                foreach ($questions as $value) {
                    $ids[] = $value['question_id'];
                }
                $condition['question_id'] = array("in", $ids);
                $condition['status'] = QuestionnaireModel::ANSWER_ACTIVE;
                //--获取所有选项--
                $questions_options = M("questionnaire_questions_options")->where($condition)->order("id asc")->select();
                if (!empty($questions_options)) {
                    //1、分支题目--
                    //1-1、汇总所有的分支题目id放入$branch_question_ids中--
                    $branch_questions = $branch_question_ids = $branch_types = array();
                    foreach ($questions_options as $key3 => $value3) {
                        $reserve = explode(",", $value3["reserve"]);
                        foreach ($reserve as $key_res => $value_res) {
                            if (!in_array($value_res, $branch_question_ids)) {
                                array_push($branch_question_ids, $value_res);
                            }
                        }
                    }
                    //1-2、查询所有分支题目
                    if (!empty($branch_question_ids)) {
                        $where_branch["id"] = array("IN", $branch_question_ids);
                        $where_branch["status"] = QuestionnaireModel::QUESTION_ACTIVE;
                        $where_branch["type"] = QuestionnaireModel::TYPE_BRANCH;
                        $branch_question_list = M("questionnaire_questions")->where($where_branch)
                            ->order("displayorder asc")->select();
                        if (!empty($branch_question_list)) {
                            $i = 1;
                            foreach ($branch_question_list as $key_b_q_list => $value_b_q_list) {
                                //--$branch_sort存储所有分支题目的顺序，$branch_questions存储分支题目信息--
                                $branch_sort[$value_b_q_list["id"]][] = $i;
                                $branch_questions[$value_b_q_list["id"]] = array(
                                    'question_id' => $value_b_q_list["id"],
                                    'title' => $value_b_q_list["title"],
                                    'sort_id' => 0,
                                    'is_single' => $value_b_q_list['is_single'],
                                    'type' => QuestionnaireModel::QUESTION_TYPE_TEXT,
                                    'options' => array(),
                                );
                            }
                        }
                    }
                    //1-3、查询所有分支题目选项
                    if (!empty($branch_question_ids)) {
                        $where_branch_options['question_id'] = array("in", $branch_question_ids);
                        $where_branch_options['status'] = QuestionnaireModel::ANSWER_ACTIVE;
                        //---$branch_options存储数据库中查询的所有的分支题目选项,$branch_types存储以题目id为key的分支类型数组--
                        //--$branch_questions_options存储以题目id为key的分支选项数组--
                        $branch_options = M("questionnaire_questions_options")->where($where_branch_options)
                            ->order("id asc")->select();
                        if (!empty($branch_options)) {
                            foreach ($branch_options as $key_b_options => $value_b_options) {
                                $branch_types[$value_b_options["question_id"]] = QuestionnaireModel::QUESTION_TYPE_TEXT;
                            }
                            foreach ($branch_options as $key_b_options => $value_b_options) {
                                if (!empty($value_b_options["title_image"])) {
                                    $branch_types[$value_b_options["question_id"]] = QuestionnaireModel::QUESTION_TYPE_IMAGE;
                                }
                                $branch_questions_options[$value_b_options["question_id"]][] = array(
                                    'id' => $value_b_options["id"],
                                    'title' => $value_b_options["title"],
                                    'title_image' => $value_b_options["title_image"] ?
                                        C('SITE_URL') . $value_b_options["title_image"] : "",
                                    'correct_answer' => $value_b_options["correct_answer"],
                                    'is_extra' => $value_b_options["is_extra"]
                                );
                            }
                        }
                    }
                    //1-4、$branch_questions分支题目拼接，重置分支题目的题目类型，设置分支题目的选项----
                    if (!empty($branch_questions)) {
                        foreach ($branch_questions as &$value_b_questions) {
                            $value_b_questions["type"] = $branch_types[$value_b_questions["question_id"]];
                            $value_b_questions["options"] = $branch_questions_options[$value_b_questions["question_id"]];
                        }
                    }
                    //2、主干题目
                    //2-1、所有主干题目选项
                    $types = $branch_child = $options = array();
                    foreach ($questions_options as $key_q_options => $value_q_options) {
                        $types[$value_q_options["question_id"]] = QuestionnaireModel::QUESTION_TYPE_TEXT;//默认文字题目
                    }
                    foreach ($questions_options as $key_q_options => $value_q_options) {
                        if (!empty($value_q_options["title_image"])) {
                            $types[$value_q_options["question_id"]] = QuestionnaireModel::QUESTION_TYPE_IMAGE;
                        }
                        //---$branch_child存储题目的分支题目详情--
                        if (!empty($value_q_options["reserve"])) {
                            $reserve = explode(",", $value_q_options["reserve"]);
                            foreach ($reserve as $key_reserve => $value_reserve) {
                                $branch_child[$value_q_options["id"]][] = $branch_questions[$value_reserve];
                            }
                        }
                        //--$options存储所有选项信息，以题目id为key--
                        $options[$value_q_options["question_id"]][] = array(
                            'id' => $value_q_options["id"],
                            'title' => $value_q_options["title"],
                            'title_image' => $value_q_options["title_image"] ?
                                C('SITE_URL') . $value_q_options["title_image"] : "",
                            'correct_answer' => $value_q_options["correct_answer"],
                            'is_extra' => $value_q_options["is_extra"],
                            'branch_questions' => !empty($value_q_options["reserve"]) ?
                                $branch_child[$value_q_options["id"]] : array()
                        );
                    }
                    //2-2、所有主干题目-----
                    $questions_i = 1;
                    foreach ($questions as &$value) {
                        $value['sort_id'] = $questions_i;
                        $value['type'] = $types[$value['question_id']];
                        $value['options'] = $options[$value['question_id']];
                        if (!empty($value['options'])) {
                            foreach ($value['options'] as &$value_options) {
                                if (!empty($value_options['branch_questions'])) {//--有分支题目--
                                    $value_v_b_q_i = 1;
                                    foreach ($value_options['branch_questions'] as &$value_v_b_questions) {
                                        $value_v_b_questions["sort_id"] = $questions_i . "." . $value_v_b_q_i++;
                                    }
                                }
                            }
                        }
                        $questions_i++;
                    }
                }
                $questionnaire['background_question'] = $questionnaire['background_question'] ?
                    C('SITE_URL') . $questionnaire['background_question'] :
                    C('SITE_URL') . '/Public/images/questionnaire/question_background.jpg';
                $this->ajaxReturn(array('status' => 1, 'msg' => '获取问卷测试题目成功',
                    'theme_color' => $questionnaire['theme_color'],
                    'background_question' => $questionnaire['background_question'], 'questions' => $questions));
            } else {
                $this->ajaxReturn(array('status' => -1, 'msg' => '暂无问卷测试题目'));
            }
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => '暂无问卷测试题目'));
        }

    }

    //随机题库
    private function getRandomQuestion($id)
    {
        $where["id"] = $id;
        $where["status"] = QuestionnaireModel::QUESTIONNAIRE_ACTIVE;
        $questionnaire = M("questionnaire")->where($where)
            ->field("random_condition1,random_condition2,random_condition3")->find();
        $return1 = $return2 = $return3 = array();
        if ($questionnaire['random_condition1']) {
            $random_condition1 = unserialize($questionnaire['random_condition1']);
            $questions1 = M("questionnaire_questions")->where(["questionnaire_id" => $id, "status" => QuestionnaireModel::QUESTION_ACTIVE, "displayorder" => array(array('lt', $random_condition1['from']), array('gt', $random_condition1['to']), "or")])->field("displayorder")->select();
            if (!empty($questions1)) {
                foreach ($questions1 as $key => $value) {
                    $ids1[] = $value['displayorder'];
                }
            }
            $where_return1['questionnaire_id'] = $id;
            $where_return1['status'] = QuestionnaireModel::QUESTION_ACTIVE;
            $where_return1['displayorder'] = array('between', array($random_condition1['from'], $random_condition1['to']));
            $return_rand1 = M('questionnaire_questions')->where($where_return1)->limit($random_condition1['count'])
                ->order('rand()')->field('displayorder')->select();
            if (!empty($return_rand1)) {
                foreach ($return_rand1 as $value) {
                    $return1[] = $value['displayorder'];
                }
            }
        }
        if ($questionnaire['random_condition2']) {
            $random_condition2 = unserialize($questionnaire['random_condition2']);
            $questions2 = M("questionnaire_questions")->where(["questionnaire_id" => $id, "status" => QuestionnaireModel::QUESTION_ACTIVE, "displayorder" => array(array('lt', $random_condition2['from']), array('gt', $random_condition2['to']), "or")])->field("displayorder")->select();
            if (!empty($questions2)) {
                foreach ($questions2 as $key => $value) {
                    $ids2[] = $value['displayorder'];
                }
            }
            $where_return2['questionnaire_id'] = $id;
            $where_return2['status'] = QuestionnaireModel::QUESTION_ACTIVE;
            $where_return2['displayorder'] = array('between', array($random_condition2['from'], $random_condition2['to']));
            $return_rand2 = M('questionnaire_questions')->where($where_return2)->limit($random_condition2['count'])
                ->order('rand()')->field('displayorder')->select();
            if (!empty($return_rand2)) {
                foreach ($return_rand2 as $value) {
                    $return2[] = $value['displayorder'];
                }
            }
        }
        if ($questionnaire['random_condition3']) {
            $random_condition3 = unserialize($questionnaire['random_condition3']);
            $questions3 = M("questionnaire_questions")->where(["questionnaire_id" => $id, "status" => QuestionnaireModel::QUESTION_ACTIVE, "displayorder" => array(array('lt', $random_condition3['from']), array('gt', $random_condition3['to']), "or")])->field("displayorder")->select();
            if (!empty($questions3)) {
                foreach ($questions3 as $key => $value) {
                    $ids3[] = $value['displayorder'];
                }
            }
            $where_return3['questionnaire_id'] = $id;
            $where_return3['status'] = QuestionnaireModel::QUESTION_ACTIVE;
            $where_return3['displayorder'] = array('between', array($random_condition3['from'], $random_condition3['to']));
            $return_rand3 = M('questionnaire_questions')->where($where_return3)->limit($random_condition3['count'])
                ->order('rand()')->field('displayorder')->select();
            if (!empty($return_rand3)) {
                foreach ($return_rand3 as $value) {
                    $return3[] = $value['displayorder'];
                }
            }
        }
        $return = array_merge($return1, $return2, $return3);
        $return = array_flip(array_flip($return));
        if (!empty($ids3) && !empty($ids2)) {
            $ids = array_intersect($ids1, $ids2, $ids3);
        } elseif (!empty($ids2)) {
            $ids = array_intersect($ids1, $ids2);
        } else {
            $ids = $ids1;
        }
        if (!empty($ids)) {
            $return = array_merge($return, $ids);
        }
        return $return;
    }

    private function _newHeadUrl($headurl)
    {
        $new_headurl = "";
        if (!empty($headurl)) {
            $headurl_arr = explode("/", $headurl);
            $new_headurl = "";
            if (!empty($headurl_arr)) {
                array_pop($headurl_arr);
                foreach ($headurl_arr as $key_h_arr => $value_h_arr) {
                    $new_headurl = $new_headurl . $value_h_arr . "/";
                }
            }
            $new_headurl = $new_headurl . "64";
        }
        return $new_headurl;
    }

    private function _downloadWxHead($new_headurl, $file)
    {
        $ch = curl_init($new_headurl);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        curl_close($ch);

        $local_file = fopen($file, 'w');
        fwrite($local_file, $package);
        fclose($local_file);
    }

    //答第一道题目
    public function beginQuestionnaire()
    {
        $id = I("post.id", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        $headurl = session('questionnaire_headimgurl_' . $id) ? session('questionnaire_headimgurl_' . $id) : '';
        if (strlen($headurl) > 0) {
            $name = session('questionnaire_openid_' . $id) . ".jpg";
            $save_path = "Public/Uploads/wx_visit_head/questionnaire/" . $id . "/";
            if (!is_dir($save_path)) mkdir($save_path);
            $file = $save_path . $name;
            if (!file_exists($file)) {
                //1、微信头像地址处理
                $new_headurl = $this->_newHeadUrl($headurl);
                //2、下载头像图片
                $this->_downloadWxHead($new_headurl, $file);
            }
            $headurl = "/" . $file;
        }
        $fans = array(
            'questionnaire_id' => $id,
            'openid' => session('questionnaire_openid_' . $id),
            'ip' => get_client_ip(),
            'date' => date("Y-m-d"),
            'startdate' => date("Y-m-d H:i:s"),
            'phone_type' => $this->phoneType(),
            'reserve' => $headurl,
            'nickname' => session('questionnaire_nickname_' . $id) ? json_encode(session('questionnaire_nickname_' . $id)) : ''
        );
        $added = M("questionnaire_fans")->add($fans);
        if ($added) {
            $this->ajaxReturn(array('status' => 1, 'fansId' => $added, 'msg' => '添加用户信息成功'));
        } else {
            $this->ajaxReturn(array('status' => -1, 'fansId' => 0, 'msg' => '添加用户信息失败'));
        }
    }

    //答最后一道题目
    public function finishQuestionnaire()
    {
        $id = I("post.fansId", -1, "");
        $answers = I("post.answers", "", "");
        $extra = I("post.extra", "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        if (!$answers || $answers == "") {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数answers'));
        }
        $scores = $this->getScores($answers);       //计算总分
        $questionnaire = M("questionnaire_fans")->where(['id' => $id])->field("startdate")->find();
        $time = time();
        $duration = $time - strtotime($questionnaire['startdate']);
        $data = array(
            'enddate' => date("Y-m-d H:i:s", $time),
            'duration' => $duration >= 0 ? $duration : 0,
            'scores' => $scores,
            'answer' => $answers
        );
        $updated = M("questionnaire_fans")->where(['id' => $id])->save($data);

        //--答题选项统计开始---
        $answer_arr = explode("|", $answers);
        $extra_arr = explode('|', $extra);
        $option_id_arr = $datas = $extra_data = array();
        if(!empty($extra_arr)){
            foreach ($extra_arr as $value_extra){
                $extra_option = explode(',', $value_extra);
                $extra_data[$extra_option[0]] = $extra_option[1];
            }
        }
        foreach ($answer_arr as $answer_each) {
            $answer_str_arr = explode(",", $answer_each);
            if (!empty($answer_str_arr[1])) {
                if (stripos($answer_str_arr[1], ";")) {
                    $answer_opt_arr = explode(";", $answer_str_arr[1]);
                    foreach ($answer_opt_arr as $answer_opt) {
                            $extra_answer = isset($extra_data[$answer_opt]) ? $extra_data[$answer_opt] : '';
                            $datas[] = ["fans_id" => $id, "question_id" => $answer_str_arr[0],
                                "option_id" => $answer_opt, "extra_answer" => $extra_answer];
                        $option_id_arr[] = $answer_opt;
                    }
                } else {
                        $extra_answer = isset($extra_data[$answer_str_arr[1]]) ? $extra_data[$answer_str_arr[1]] : '';
                        $datas[] = ["fans_id" => $id, "question_id" => $answer_str_arr[0],
                            "option_id" => $answer_str_arr[1], "extra_answer" => $extra_answer];
                    $option_id_arr[] = $answer_str_arr[1];
                }
            }
        }
        M("questionnaire_fans_ans")->addAll($datas);
        $cond_option['id'] = array("IN", $option_id_arr);
        M("questionnaire_questions_options")->where($cond_option)->setInc('count');
        //---答题选项统计结束--

        if ($updated) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '保存用户答题数据成功'));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => '保存用户答题数据失败'));
        }
    }

    private function getScores($answers)
    {
        $questions_options = explode("|", $answers);
        $scores = 0;
        $questions = array();
        if (!empty($questions_options)) {
            foreach ($questions_options as $value1) {
                $item = explode(",", $value1);
                $questions[$item[0]] = $item[1];
            }
            if (!empty($questions)) {
                $list = M("questionnaire_questions_options")->where(["question_id" => array("in", array_keys($questions)), "status" => QuestionnaireModel::ANSWER_ACTIVE])->getField("id,score");
                foreach ($questions as $question_id => $options) {
                    if (strpos($options, ";")) {
                        $option_arr = explode(";", $options);
                        foreach ($option_arr as $option) {
                            if (array_key_exists($option, $list)) {
                                $scores += $list[$option];
                            }
                        }
                    } else {
                        if (array_key_exists($options, $list)) {
                            $scores += $list[$options];
                        }
                    }
                }
            }
        }
        return $scores;
    }

    public function ending()
    {
        $id = I("get.id", -1, "");
        $fansId = I("get.fansId", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        if (!$fansId || $fansId == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数fansId'));
        }
        $questionnaire = M("questionnaire")->where(['id' => $id])
            ->field("theme_color,ending_play,ending_share,ending_background,ending_jump,ending_jumplink,ending_qrcode,has_qrcode")->find();
        $fans_scores = M("questionnaire_fans")->where(['id' => $fansId, 'status' => QuestionnaireModel::STATISTICS_ACTIVE])
            ->getField("scores");
        $questionnaire_ending = M("questionnaire_ending")->where(['questionnaire_id' => $id, 'lower_limit' => array('elt', $fans_scores), 'upper_limit' => array('egt', $fans_scores), 'status' => QuestionnaireModel::ENDING_ACTIVE])
            ->field("title,info,activity_title,activity_url,ending_image")->find();
        if (empty($questionnaire_ending)) {
            $questionnaire_ending = M("questionnaire_ending")->where(['questionnaire_id' => $id, 'lower_limit' => 0, 'upper_limit' => 0, 'status' => QuestionnaireModel::ENDING_ACTIVE])
                ->field("title,info,activity_title,activity_url,ending_image")->find();
        }
        //ending页默认值
        if (empty($questionnaire_ending)) {
            $questionnaire_ending = array(
                'title' => "Congratulations",
                'info' => "邀请你的好友一起来测一测",
                'activity_title' => "",
                'activity_url' => "",
                'ending_image' => "/Public/images/questionnaire/reward.gif"
            );
        }
        $questionnaire['ending_play'] = $questionnaire['ending_play'] ? C("SITE_URL") . $questionnaire['ending_play'] : C('SITE_URL') . '/Public/images/questionnaire/ending_play.jpg';
        $questionnaire['ending_share'] = $questionnaire['ending_share'] ? C("SITE_URL") . $questionnaire['ending_share'] : C('SITE_URL') . '/Public/images/questionnaire/ending_share.jpg';
        $questionnaire['ending_background'] = $questionnaire['ending_background'] ? C("SITE_URL") . $questionnaire['ending_background'] : C('SITE_URL') . '/Public/images/questionnaire/ending_background.jpg';
        $questionnaire['ending_jump'] = $questionnaire['ending_jump'] ? C("SITE_URL") . $questionnaire['ending_jump'] :
            C("SITE_URL") . '/Public/images/questionnaire/theme' . $questionnaire["theme_color"] . '_follow.png';
        $questionnaire['ending_jumplink'] = $questionnaire['ending_jumplink'] ? $questionnaire['ending_jumplink'] : '';
        $questionnaire['ending_qrcode'] = $questionnaire['ending_qrcode'] ? C("SITE_URL") . $questionnaire['ending_qrcode'] : C('SITE_URL') . '/Public/images/home/zbgyEcode.jpg';
        if (!empty($questionnaire_ending)) {
            $questionnaire_ending['info'] = str_replace('[score]', $fans_scores, $questionnaire_ending['info']);
            $questionnaire_ending['ending_image'] = $questionnaire_ending['ending_image'] ? C("SITE_URL") . $questionnaire_ending['ending_image'] : C('SITE_URL') . '/Public/images/questionnaire/reward.gif';
        }
        if (!empty($questionnaire)) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '查询结束页信息成功', 'ending' => $questionnaire,
                'application' => $questionnaire_ending));
        } else {
            $this->ajaxReturn(array('status' => -1, 'msg' => '查询结束页信息失败'));
        }
    }

    //缓存pv、uv
    private function _statistics($id)
    {
        if (!$id || $id != -1) {
            $cache = S('questionnaire_puv_'.$id);
            if (!$cache) {
                S('questionnaire_puv_'.$id, array('date' => date('Y-m-d'), 'pv' => 1, 'uv' => 1),
                    array('expire' => 800000));
            } else {
                if ($cache['date'] == date('Y-m-d')) {
                    $pv = $cache['pv'] + 1;
                    $uv = $cache['uv'];
                    $cookie_uv = cookie("questionnaire" . $id . date("Y-m-d"));
                    if(!$cookie_uv){
                        $time = strtotime(date("Y-m-d", strtotime("+1 day")) . " 00:00:00") - time();
                        cookie("questionnaire" . $id . date("Y-m-d"), date("Y-m-d"), $time);
                        $uv = $cache['uv'] + 1;
                    }
                    S('questionnaire_puv_'.$id, array('date' => date('Y-m-d'), 'pv' => $pv, 'uv' => $uv),
                        array('expire' => 800000));
                } else {
                    $where["questionnaire_id"] = $id;
                    $where["date"] = $cache['date'];
                    $stat = M('questionnaire_statistics')->where($where)->find();
                    if (!empty($stat)) {
                        M("questionnaire_statistics")->where($where)
                            ->save(array('page_view' => $cache['pv'], 'reserve' => $cache["uv"]));
                    } else {
                        $data = array(
                            'questionnaire_id' => $id,
                            'date' => $cache['date'],
                            'page_view' => $cache['pv'],
                            'reserve' => $cache['uv']
                        );
                        M("questionnaire_statistics")->add($data);
                    }
                    S('questionnaire_puv_'.$id, array('date' => date('Y-m-d'), 'pv' => 1, 'uv' => 1),
                        array('expire' => 800000));
                }
            }
        }
    }

    /*移动端设备判断*/
    private function phoneType()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (stripos($user_agent, "iPhone") !== false) {
            $brand = 'iPhone';
        } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false || strpos($user_agent, "SM-") !== false) {
            $brand = '三星';
        } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
            $brand = '华为';
        } else if (stripos($user_agent, "Lenovo") !== false) {
            $brand = '联想';
        } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
            $brand = '小米';
        } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
            $brand = '红米';
        } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false || strpos($user_agent, "5910") !== false) {
            $brand = '酷派';
        } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
            $brand = '中兴';
        } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false || strpos($user_agent, "R2017") !== false) {
            $brand = 'OPPO';
        } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
            $brand = 'HTC';
        } else if (stripos($user_agent, "vivo") !== false) {
            $brand = 'vivo';
        } else if (stripos($user_agent, "K-Touch") !== false) {
            $brand = '天语';
        } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false || stripos($user_agent, "NX40") !== false) {
            $brand = '努比亚';
        } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false || strpos($user_agent, "M355") !== false) {
            $brand = '魅族';
        } else if (stripos($user_agent, "DOOV") !== false) {
            $brand = '朵唯';
        } else if (stripos($user_agent, "GFIVE") !== false) {
            $brand = '基伍';
        } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
            $brand = '金立';
        } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
            $brand = '海信';
        } else if (stripos($user_agent, "Nokia") !== false) {
            $brand = '诺基亚';
        } else {
            $brand = '其他手机';
        }
        return $brand;
    }

    public function getWxShare()
    {
        $id = I("get.id", -1, "");
        $fansId = I("get.fansId", -1, "");
        if (!$id || $id == -1) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '未传入参数id'));
        }
        //分享数据
        $where_questionnaire["id"] = $id;
        $questionnaire = M("questionnaire")->where($where_questionnaire)
            ->field("title,share_title,share_desc,share_link,share_image")->find();
        $share_data = array(
            'share_link' => $questionnaire['share_link'] ? $questionnaire['share_link'] :
                C('SITE_URL') . '/Wap/Questionnaire/index?id=' . $id,
            'share_image' => $questionnaire['share_image'] ? C('SITE_URL') . $questionnaire['share_image'] :
                '/Public/images/questionnaire/share_image.jpg',
        );
        if (!$fansId || $fansId == -1) {
            $where_ending["questionnaire_id"] = $id;
            $where_ending["lower_limit"] = 0;
            $where_ending["upper_limit"] = 0;
            $where_ending["status"] = QuestionnaireModel::ENDING_ACTIVE;
            $questionnaire_ending = M("questionnaire_ending")->where($where_ending)->field("title, info")->find();
            $questionnaire_ending['info'] = str_replace('[score]', 0, $questionnaire_ending['info']);
            if ($questionnaire['share_title']) {
                $share_data['share_title'] = $questionnaire['share_title'];
            } else {
                $share_data['share_title'] = $questionnaire['title'];
            }
            if ($questionnaire['share_desc']) {
                $share_data['share_desc'] = $questionnaire['share_desc'];
            } else {
                $share_data['share_desc'] = '邀请你的好友一起来测一测！';
            }
            $this->ajaxReturn(array('status' => 1, 'msg' => '首页分享内容', 'share_data' => $share_data));
        } else {
            $where_fans["id"] = $fansId;
            $where_fans["status"] = QuestionnaireModel::STATISTICS_ACTIVE;
            $fans_scores = M("questionnaire_fans")->where($where_fans)->getField("scores");
            $where_ending["questionnaire_id"] = $id;
            $where_ending["lower_limit"] = array('elt', $fans_scores);
            $where_ending["upper_limit"] = array('egt', $fans_scores);
            $where_ending["status"] = QuestionnaireModel::ENDING_ACTIVE;
            $questionnaire_ending = M("questionnaire_ending")->where($where_ending)->field("title, info")->find();
            if (empty($questionnaire_ending)) {
                $where_ending_empty["questionnaire_id"] = $id;
                $where_ending_empty["lower_limit"] = 0;
                $where_ending_empty["upper_limit"] = 0;
                $where_ending_empty["status"] = QuestionnaireModel::ENDING_ACTIVE;
                $questionnaire_ending = M("questionnaire_ending")->where($where_ending_empty)->field("title, info")
                    ->find();
            }
            $questionnaire_ending['info'] = str_replace('[score]', $fans_scores, $questionnaire_ending['info']);
            if ($questionnaire['share_title']) {
                $share_data['share_title'] = $questionnaire['share_title'];
            } else {
                $share_data['share_title'] = $questionnaire_ending['title'] ? $questionnaire_ending['title'] :
                    'Congratulations';
            }
            if ($questionnaire['share_desc']) {
                $share_data['share_desc'] = $questionnaire['share_desc'];
            } else {
                $share_data['share_desc'] = $questionnaire_ending['info'] ? $questionnaire_ending['info'] :
                    '邀请你的好友一起来测一测！';
            }
            $this->ajaxReturn(array('status' => 1, 'msg' => '结束页分享内容', 'share_data' => $share_data));
        }
    }
    public function test(){
        $ch = curl_init("http");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        curl_close($ch);
    }
}